local skynet = require "skynet"
local socket = require "socket"
require "skynet.manager"	-- import skynet.register
require "math"
require "public"

local json = require "cjson"
local ErrNo = require "common/ErrNo" 

CMD = {}
local rooms = {}
local ROOM_PLAERY_NUM = 5

 
function CMD.create_room(data)
	local room_id = math.floor(data.room_id) 
	if not room_id then 
		return nil,nil -- 房间存在
	end 
	if rooms[room_id] ~= nil then
		return nil,nil -- 房间存在
	end
	room_fd = skynet.newservice("douniu_room")

    rooms[room_id] = {}
    rooms[room_id].room_fd = room_fd
    rooms[room_id].count = 1 
	if not data.ruleType then 
		data.ruleType = 0 --0通赔下庄  1开局抢庄 2牛牛大当庄 3看牌抢庄  
	end
	if not data.total_ju or data.total_ju ~= 20 then 
		data.total_ju = 10
	end 
	if not data.room_odds then 
		data.room_odds = 1  
	end
    skynet.call( room_fd, "lua", "start", room_id, data)
	skynet.error("[douniu_hall] 创建房间: "..room_id, json.encode(data))
    return room_id,room_fd
end

function CMD.join_room(id)
	-- 房间状态
	local room_id = math.floor(id)
	if rooms[room_id] == nil then
		return ErrNo.ROOM_NOT_EXISTS,nil -- 房间不存在
	end
	if rooms[room_id].count >= ROOM_PLAERY_NUM then
		return ErrNo.ROOM_FULL,nil
	end
	
	return room_id,rooms[room_id].room_fd
end


function CMD.join_room_again(room_id,uid)
	local room_id = math.ceil(room_id)
	if rooms[room_id] == nil then
		return ErrNo.ROOM_NOT_EXISTS,nil -- 房间不存在
	end
		
	return room_id,rooms[room_id].room_fd
end

function CMD.get_rooms(room_id)
	local room_id = math.floor(room_id)
 	if rooms[room_id] == nil then
		return nil -- 房间不存在
	end 
	return rooms[room_id].room_fd
end

function CMD.room_status(id,data)  
	local id = math.floor(id)
    rooms[id].count = data.count 
end

function CMD.destory(id) 
	if id then 
		local room_id = math.ceil(id) 
		skynet.call("MG_SAVE", "lua", "clean_room_redis", room_id)
		rooms[id] = nil
	else
		skynet.error("id had destory")
	end
end

skynet.start(function()
	skynet.dispatch("lua", function(_,_, command, ...)
		local f = CMD[command]
		skynet.ret(skynet.pack(f(...)))
	end)
	skynet.register "DOUNIU_HALL"
end)

